import os
import datetime

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext.db import stats
from google.appengine.ext import deferred

import ckeynsecret

from myspace.myspaceapi import MySpace
from models import Subscription, Activity, RawFeed
from entity_deleter import *

RAWFEED_CLEANUP_MAX_AGE_SECONDS = (1 * 24 * 60 * 60)  # 1 days
ACTIVITY_CLEANUP_MAX_AGE_SECONDS = (1 * 24 * 60 * 60)  # 1 days

class AdminPageHandler(webapp.RequestHandler):        
    def get(self):
        op = self.request.get('op', default_value=None)
        if op is None:
            self.show_admin_page()
        else:
            if op == 'get_subscription':
                self.get_subscription()
            if op == 'purge_old_activities': # Will get called when the purge activity crob job is scheduled
                self.purge_old_activities()
            if op == 'purge_old_rawfeeds': # Will get called when the purge raw feeds crob job is scheduled
                self.purge_old_rawfeeds()
                                                   
    def post(self):
        op = self.request.get('op', default_value=None)
        if op is None:
            self.show_admin_page()
        else:
            if op == 'delete_activities':
                #Delete 500 activities at a time
                num_activities = self.get_activity_count()
                while num_activities > 0:
                    self.delete_activities( 500 )
                    num_activities = num_activities - 500
            if op == 'delete_subscriptions':
                self.delete_subscriptions()
                
    def show_admin_page(self):
        ms = MySpace(ckeynsecret.CONSUMER_KEY, ckeynsecret.CONSUMER_SECRET)
        ms_subscriptions = ms.get_subscription("@all")
        
        template_data = {
                'ms_subscriptions' : ms_subscriptions,
                'activity_count' : self.get_activity_count(),
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
        return self.response.out.write(template.render(path, template_data))
    
    def get_activity_count(self):
        aactivity_stat = stats.KindStat.all().filter('kind_name =', 'Activity').get()
        if aactivity_stat is None:
            activity_count = 'Unavailable'
        else:
            activity_count = aactivity_stat.count
        return activity_count
    
    def delete_activities(self, count):
        try:
            q = db.GqlQuery("SELECT * FROM Activity")
            db.delete(q.fetch(count))
        except Exception, e:
            self.response.out.write(repr(e)+'\n')
            pass       
        self.show_admin_page()
        
    def get_subscription(self):
        subscription_id = self.request.get('id', default_value=None)
        if subscription_id is not None:
            self.show_subscription_info_page(subscription_id)
 
    def delete_subscriptions(self):
        ms = MySpace(ckeynsecret.CONSUMER_KEY, ckeynsecret.CONSUMER_SECRET)
        subscription_ids = self.request.get_all('subscription_id')
        for id in subscription_ids:
            # Delete subscription on the MySpace side            
            ms.delete_subscription(id)
            # Delete subscription entry on app engine datastore
            Subscription.delete_subscription(id)
        self.show_admin_page()
        
    def show_subscription_info_page(self, subscription_id):
        ms = MySpace(ckeynsecret.CONSUMER_KEY, ckeynsecret.CONSUMER_SECRET)
        sub_info = ms.get_subscription(subscription_id)
        self.response.out.write(sub_info);
        self.response.set_status(200)
        
    def purge_old_activities(self):
        now = datetime.datetime.utcnow()
        threshold = (now - datetime.timedelta(seconds=RAWFEED_CLEANUP_MAX_AGE_SECONDS))
        mapper = OldEntityDeleter(Activity, threshold)
        deferred.defer(mapper.run)

    def purge_old_rawfeeds(self):
        now = datetime.datetime.utcnow()
        threshold = (now - datetime.timedelta(seconds=RAWFEED_CLEANUP_MAX_AGE_SECONDS))
        mapper = OldEntityDeleter(RawFeed, threshold)
        deferred.defer(mapper.run)
